﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.IO;
using System.Collections.Specialized;
using System.Web.UI;

namespace Axe.Web.Controls.Providers
{
    public class WikiTextFileProvider : WikiContentProvider
    {
        string workingDirectory;
        string absWorkDirectory;
        string globalWikiDirName = "_Global";

        public WikiTextFileProvider()
        {
        }

        public override void Initialize(string name, NameValueCollection config)
        {
            base.Initialize(name, config);

            workingDirectory = config["baseDir"];

            if (workingDirectory.StartsWith("~/"))
                absWorkDirectory = HttpContext.Current.Server.MapPath(workingDirectory);
            else
                absWorkDirectory = workingDirectory;

            FileSystem.EnsureDirectory(absWorkDirectory);
        }

        private string GetWikiContentFilePath(string contentKey, WikiContentControlIdentifierMode mode, Page pageOwner)
        {
            string path = null;

            if (mode == WikiContentControlIdentifierMode.SiteGlobal)
            {
                string location = Path.Combine(absWorkDirectory, globalWikiDirName);
                FileSystem.EnsureDirectory(location);
                path = Path.Combine(location, contentKey + ".wiki");
            }
            else
            {
                string pageLocation = pageOwner.AppRelativeVirtualPath.Replace("~/", "");
                string absLocation = Path.Combine(absWorkDirectory, pageLocation);

                FileSystem.EnsureDirectory(absLocation);
                path = Path.Combine(absLocation, contentKey + ".wiki");
            }

            return path;
        }

        public override void RegisterWikiControl(string contentKey, Page pageOwner, WikiContentControlIdentifierMode mode)
        {
            string file = GetWikiContentFilePath(contentKey, mode, pageOwner);

            if (!File.Exists(file))
            {
                using (File.Create(file)) { };
            }
        }

        public override string GetContent(string contentKey, Page pageOwner,WikiContentControlIdentifierMode mode)
        {
            string file = GetWikiContentFilePath(contentKey, mode, pageOwner);

            if (!File.Exists(file))
            {
                return String.Empty;
            }
            else
            {
                return File.ReadAllText(file,Encoding.UTF8);
            }
        }

        public override void UpdateContent(string contentKey, string contentText, Page ownerPage, WikiContentControlIdentifierMode mode)
        {
            string file = GetWikiContentFilePath(contentKey, mode, ownerPage);
            File.WriteAllText(file, contentText, Encoding.UTF8);
        }
    }
}
